package persistence

import (
	"context"

	"baseService/internal/domain/entities"
	"baseService/internal/domain/repositories"

	"gorm.io/gorm"
)

// exampleRepositoryImpl 示例仓储实现
type exampleRepositoryImpl struct {
	repositories.BaseRepository[entities.Example]
	db *gorm.DB
}

// NewExampleRepository 创建示例仓储实例
func NewExampleRepository(db *gorm.DB) repositories.ExampleRepository {
	return &exampleRepositoryImpl{
		BaseRepository: NewBaseRepository[entities.Example](db),
		db:             db,
	}
}

// GetByName 根据名称获取示例
func (r *exampleRepositoryImpl) GetByName(ctx context.Context, name string) (*entities.Example, error) {
	var example entities.Example
	err := r.db.WithContext(ctx).Where("name = ?", name).First(&example).Error
	if err != nil {
		return nil, err
	}
	return &example, nil
}

// GetActiveExamples 获取激活状态的示例列表
func (r *exampleRepositoryImpl) GetActiveExamples(ctx context.Context, limit int) ([]*entities.Example, error) {
	var examples []*entities.Example
	query := r.db.WithContext(ctx).Where("status = ?", entities.ExampleStatusActive)

	if limit > 0 {
		query = query.Limit(limit)
	}

	err := query.Find(&examples).Error
	return examples, err
}

// GetByStatus 根据状态获取示例列表
func (r *exampleRepositoryImpl) GetByStatus(ctx context.Context, status entities.ExampleStatus) ([]*entities.Example, error) {
	var examples []*entities.Example
	err := r.db.WithContext(ctx).Where("status = ?", status).Find(&examples).Error
	return examples, err
}

// UpdateStatus 更新示例状态
func (r *exampleRepositoryImpl) UpdateStatus(ctx context.Context, id uint, status entities.ExampleStatus) error {
	return r.db.WithContext(ctx).Model(&entities.Example{}).
		Where("id = ?", id).
		Update("status", status).Error
}
